package com.zsummer.zero.design.structure.proxy;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/**
 * cglib动态代理
 * 需要cglib的jar包
 * 使用的继承，所以final类无法实现cglib代理
 * @author zhouyujiang
 *
 */
public class Demo3 {

	public static void main(String[] args) {
		Girl girl = new Girl();
		Girl girlProxy = (Girl)new GirlInterceptor().getProxyOjbect(girl);
		girlProxy.sleep();
		girlProxy.eat();
	}
}

class Girl {
	public void eat() {
		System.out.println("girl: eat");
	}
	
	public void sleep() {
		System.out.println("girl: sleep");
	}
}

class GirlInterceptor implements MethodInterceptor{
	
	private Object target;
	
	public Object getProxyOjbect(Object target) {
		this.target = target;
		// 动态代码生成器
		Enhancer enhancer = new Enhancer();
		// 回调方法
		enhancer.setCallback(this);
		// 生成类的父类
		enhancer.setSuperclass(target.getClass());
		// 动态生成字节码并返回对象
		return enhancer.create();
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		System.out.println("proxy: start");
		Object result = method.invoke(target, args);
		System.out.println("proxy: end");
		return result;
	}
	
}
